<template>
  <div class="detection-container">
    <div class="page-header">
      <div class="page-actions">
        <el-button type="primary" @click="handleCreateTask">
          <el-icon><Plus /></el-icon>新建检测任务
        </el-button>
      </div>
    </div>

    <!-- 搜索表单 -->
     <!-- :loading="loading" -->
    <search-form
      v-model="queryParams"      
      @search="handleSearch"
      @reset="handleReset"
    >
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="name" placeholder="请输入任务名称" />
      </el-form-item>

      <!-- <el-form-item label="漏洞名称" prop="vuln_title">
        <el-input v-model="vuln_title" placeholder="请输入漏洞名称" />
      </el-form-item> -->

      <el-form-item label="时间范围" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateRangeChange"
        />
      </el-form-item>
    </search-form>

    <!-- 任务列表 -->
    <el-card class="task-list-card" v-loading="loading">
      <base-table
        :data="taskList"
        :total="total"
        :page="queryParams.page_index"
        :limit="queryParams.page_size"
        :page-sizes="[10, 20, 50, 100]"
        :loading="loading"
        :empty-text="'暂无检测任务'"
        @pagination="handlePagination"
      >
        <el-table-column prop="id" label="ID" min-width="50" />
        <el-table-column prop="name" label="任务名称" min-width="100" />
        <el-table-column prop="ip" label="目标IP" width="150" />
        <el-table-column prop="ports" label="端口范围" min-width="100" />
        <el-table-column prop="progress" label="执行进度" min-width="180">
          <template #default="{ row }">
            <el-progress
              :percentage="row.progress == null ? 0 : parseInt(row.progress)"
          /></template>
        </el-table-column>
        <el-table-column label="状态" width="115">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row)" v-if="row.status_info">{{
              row.status_info
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" min-width="150" />
        <el-table-column label="操作" width="400">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              icon="VideoPlay"
              @click="handleStartTask(row)"
              :disabled="isTaskRunning(row)"
            >
              启动
            </el-button>
            <el-button
              type="primary"
              link
              icon="Edit"
              @click="handleEditTask(row)"
              :disabled="isTaskRunning(row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              link
              icon="View"
              @click="handleViewResult(row)"
              :disabled="row.status != 5"
            >
              查看结果
            </el-button> 
            <el-button
              type="primary"
              link
              icon="View"
              @click="handleDownloadReport(row.id)"
              :disabled="row.status != 5"
            >
              下载报告
            </el-button>            
            <el-button
              type="danger"
              link
              icon="Delete"
              @click="handleDeleteTask(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </base-table>
    </el-card>

    <!-- 任务表单弹窗 -->
    <task-dialog
      v-model="taskDialogVisible"
      :task-data="currentTask"
      @submit="handleTaskSubmit"
      :isEdit="isEdit"
    />

    <!-- 结果弹窗 -->
    <result-dialog
      v-model="resultDialogVisible"
      :task-info="detailCurrentTask"
      :loading="resultLoading"
      @download-report="handleDownloadReport"
    />
  </div>
</template>

<script setup>
/**
 * 漏洞检测页面
 * @module Detection
 * @description 用于管理漏洞检测任务和查看检测结果
 */
import SearchForm from "@/components/SearchForm/index.vue";
import { Plus } from "@element-plus/icons-vue";
import {
  getTaskList,
  createTask,
  updateTask,
  deleteTask,
  startTask,
  downloadTaskReport,
} from "@/api/vulnDetection";
import TaskDialog from "./components/TaskDialog.vue";
import ResultDialog from "./components/ResultDialog.vue";
import { downloadFileFromResponse } from "@/utils/fileOpt";
import BaseTable from "@/components/BaseTable/index.vue";

// 页面状态
const loading = ref(false);
const resultLoading = ref(false);
const total = ref(0);
const taskList = ref([]);
let loopListTimer = null;

// 处理日期范围变化
const handleDateRangeChange = (val) => {
  dateRange.value = val;
};

// 处理搜索
const handleSearch = () => {
  queryParams.page_index = 1;
  fetchTaskList();
};

// 处理重置
const vuln_title = ref("");
const name = ref("");
const dateRange = ref(null);
const handleReset = () => {
  vuln_title.value = "";
  name.value = "";
  dateRange.value = null;
  // Object.keys(searchForm).forEach((key) => {
  //   searchForm[key] = "";
  // });
  fetchTaskList();
};

// 查询参数
const queryParams = reactive({
  page_index: 1,
  page_size: 10,
});

// 弹窗状态
const taskDialogVisible = ref(false);
const resultDialogVisible = ref(false);
const currentTask = ref({});
const detailCurrentTask = ref({});

// 获取任务列表
const fetchTaskList = async () => {
  loading.value = true;
  queryParams.name = name.value;
  queryParams.vuln_title = vuln_title.value;
  if (dateRange.value) {
    queryParams.start_time = dateRange.value[0];
    queryParams.end_time = dateRange.value[1];
  } else {
    queryParams.start_time = null;
    queryParams.end_time = null;
  }
  try {
    const res = await getTaskList(queryParams);
    taskList.value = res.data || [];
    total.value = res.total_items || 0;
  } catch (error) {
    console.error("获取任务列表失败", error);
    ElMessage.error("获取任务列表失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 处理任务表单提交
const handleTaskSubmit = async (formData) => {
  try {
    if (formData.id) {
      // 更新任务
      await updateTask(formData);
      ElMessage.success("更新任务成功");
    } else {
      // 创建任务
      await createTask(formData);
      ElMessage.success("创建任务成功");
    }

    // 刷新任务列表
    fetchTaskList();
  } catch (error) {
    console.error("提交任务失败", error);
    ElMessage.error("提交任务失败，请稍后重试");
  }
};

// 处理创建任务
const isEdit = ref(false);
const handleCreateTask = () => {
  currentTask.value = { name: "", ip: "", ports: "" };
  isEdit.value = false;
  taskDialogVisible.value = true;
};

// 处理编辑任务
const handleEditTask = (row) => {
  currentTask.value = { ...row };
  isEdit.value = true;
  taskDialogVisible.value = true;
};

// 处理删除任务
const handleDeleteTask = (row) => {
  ElMessageBox.confirm("确定要删除该检测任务吗？删除后无法恢复。", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const data = { id: row.id };
        await deleteTask(data);
        ElMessage.success("删除任务成功");
        fetchTaskList();
      } catch (error) {
        console.error("删除任务失败", error);
        ElMessage.error("删除任务失败，请稍后重试");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 处理启动任务
const handleStartTask = async (row) => {
  try {
    const formData = new FormData();
    formData.append("id", row.id);
    await startTask(formData);
    ElMessage.success("任务启动成功");

    // 刷新任务列表
    setTimeout(() => {
      fetchTaskList();
    }, 5000);
  } catch (error) {
    console.error("启动任务失败", error);
    ElMessage.error("启动任务失败，请稍后重试");
  }
};

// 处理查看结果
const handleViewResult = async (row) => {
  detailCurrentTask.value = { ...row };
  resultDialogVisible.value = true;
};

// 下载检测报告
const handleDownloadReport = async (taskId) => {
  try {
    ElMessage.info("正在下载报告...");

    const params = { id: taskId };
    const res = await downloadTaskReport(params);

    // 下载文件
    downloadFileFromResponse(res);

    ElMessage.success("报告下载成功");
  } catch (error) {
    console.error("下载报告失败", error);
    ElMessage.error("下载报告失败，请稍后重试");
  }
};

// 处理分页
const handlePagination = ({ page, limit }) => {
  queryParams.page_index = page;
  queryParams.page_size = limit;
  fetchTaskList();
};

// 获取状态类型
const getStatusType = (row) => {
  let status = row.status_info;
  if (!status) return "";

  if (status.includes("完成")) return "success";
  if (status.includes("进行")) return "primary";
  if (status.includes("等待")) return "info";
  if (status.includes("失败") || status.includes("异常")) return "danger";

  return "warning";
};

// 判断任务是否正在运行
const isTaskRunning = (row) => {
  if (row.start == 1) return true;
  return false;
};

// 页面加载时获取任务列表
onMounted(() => {
  fetchTaskList();
  loopListTimer = setInterval(() => {
    fetchTaskList();
  }, 5000);
});

onUnmounted(() => {
  clearInterval(loopListTimer);
});
</script>

<style lang="scss" scoped>
.detection-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    font-size: 22px;
    font-weight: bold;
  }
}

.task-list-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;

    .page-actions {
      margin-top: 10px;
    }
  }
}
:deep(.el-table td .cell) {
  min-height: auto;
}
</style>
